<?php
class CommonUtils{

	public static function createWatermark($source, $des, $watermarkPath = null)
	{
		if(is_null($watermarkPath)){
			$watermarkPath = WATERMARK_PATH;
		}

		$filetype = substr($source,strlen($source)-4,4);
		$filetype = strtolower($filetype);
		if($filetype == ".gif")  $image = @imagecreatefromgif($source);
		if($filetype == ".jpg")  $image = @imagecreatefromjpeg($source);
		if($filetype == ".png")  $image = @imagecreatefrompng($source);
		if (!$image) return false;
		$watermark = @imagecreatefrompng($watermarkPath);
		$imagewidth = imagesx($image);
		$imageheight = imagesy($image);
		$watermarkwidth =  imagesx($watermark);
		$watermarkheight =  imagesy($watermark);
		/*
		 $startwidth = (($imagewidth - $watermarkwidth)/2);
		 $startheight = (($imageheight - $watermarkheight)/2);
		 imagecopy($image, $watermark,  $startwidth, $startheight, 0, 0, $watermarkwidth, $watermarkheight);
		 */
		imagecopy($image, $watermark,  0, 0, 0, 0, $watermarkwidth, $watermarkheight);
		$offsetX = $watermarkwidth;
		$offsetY = 0;
		while( $offsetY <= ($imageheight + $watermarkheight) ) {
			while( $offsetX <= ($imagewidth + $watermarkwidth) ) {
				imagecopy($image, $watermark, $offsetX, $offsetY, 0, 0, $watermarkwidth, $watermarkheight);
				$offsetX += $watermarkwidth;
			}
			$offsetX = 0;
			$offsetY += $watermarkheight;
		}

		$filetypeDes = substr($des,strlen($des)-4,4);
		$filetypeDes = strtolower($filetypeDes);

		if($filetypeDes == ".gif") imagegif($image, $des, 100);
		if($filetypeDes == ".jpg") imagejpeg($image, $des, 100);
		if($filetypeDes == ".png") imagepng($image, $des, 9);
		imagedestroy($image);
		imagedestroy($watermark);
	}

	public static function uploadBanner($name)
	{
		$picture = "";
		if(isset($_FILES[$name]["name"]) && $_FILES[$name]["name"] != ""){
			$extension = CommonUtils::man_MIME2Ext_Image($_FILES[$name]["type"]);
			if (!empty($extension)){

				// Calulate name of picture
				$picture = date('Y-m') . CommonUtils::randomNumber(9) . '.' . $extension;

				// Copy to server
				if(!copy($_FILES[$name]["tmp_name"], UPLOADIMAGE_PATH . '/Banners/' . $picture)){
					$picture = "";
					throw new Exception('Upload Banner fail', 1);
				}
			}
		}
		return $picture;
	}

	public static function uploadPicture($name)
	{
		$picture = "";
		if(isset($_FILES[$name]["name"]) && $_FILES[$name]["name"] != ""){
			$extension = CommonUtils::man_MIME2Ext_Image($_FILES[$name]["type"]);
			if (!empty($extension)){

				// Calulate name of picture
				$picture = date('Y-m') . CommonUtils::randomNumber(9) . '.' . $extension;

				// Copy to server
				if(!copy($_FILES[$name]["tmp_name"], UPLOADIMAGE_PATH . '/Images/' . $picture)){
					$picture = "";
					throw new Exception('Upload image fail', 1);
				}
			}
			else
			{
				$picture = "";
				throw new Exception('Upload image fail', 2);
			}
		}
		return $picture;
	}

	public static function uploadFavicon($name)
	{
		$picture = "";
		if(isset($_FILES[$name]["name"]) && $_FILES[$name]["name"] != ""){
			$extension = CommonUtils::man_MIME2Ext_Ico($_FILES[$name]["type"]);
			if (!empty($extension)){

				// Calulate name of picture
				$picture = date('Y-m') . CommonUtils::randomNumber(9) . '.' . $extension;

				// Copy to server
				if(!copy($_FILES[$name]["tmp_name"], UPLOADIMAGE_PATH . '/Images/' . $picture)){
					$picture = "";
					throw new Exception('Upload image fail', 1);
				}
			}
			else
			{
				$picture = "";
				throw new Exception('Upload image fail', 2);
			}
		}
		return $picture;
	}

	public static function uploadPictureEx($name){
		$picture = "";
		if(isset($_FILES[$name]["name"]) && $_FILES[$name]["name"] != ""){
			$extension = CommonUtils::man_MIME2Ext_Image($_FILES[$name]["type"]);
			if (!empty($extension)){

				// Calulate name of picture
				$picture = date('Y-m') . CommonUtils::randomNumber(9) . '.' . $extension;

				//echo $picture;
				// Copy to server
				if(!copy($_FILES[$name]["tmp_name"], UPLOADIMAGE_PATH . '/Images/' . $picture)){
					$picture = "";
					//throw new Exception('Upload image fail', 1);
				}
				else
				{
					$scaleImageThread = new ScaleImageThread();
					$scaleImageThread->run( UPLOADIMAGE_PATH . '/Images/' . $picture, UPLOADIMAGE_PATH . '/Thumbnails/' . $picture, 210, 120);
				}
			}
		}
		return $picture;
	}

	public static function uploadZip($name)
	{
		$fileName = "";
		if(isset($_FILES[$name]["name"]) && $_FILES[$name]["name"] != ""){
			$extension = CommonUtils::getExtension($_FILES[$name]["name"]);
			if (!empty($extension) && ($extension == 'zip' || $extension == 'rar'))
			{

				// Calulate name of picture
				$fileName = date('Y-m') . CommonUtils::randomNumber(9) . '.' . $extension;

				// Copy to server
				if(!copy($_FILES[$name]["tmp_name"], UPLOADIMAGE_PATH . '/Downloads/' . $fileName)){
					$fileName = "";
					throw new Exception('Upload image fail', 1);
				}
			}
			else
			{
				$fileName = "";
				throw new Exception('Upload ZIP file fail', 2);
			}
		}
		return $fileName;
	}

	public static function uploadVideo($name)
	{
		$video = "";
		if(isset($_FILES[$name]["name"]) && $_FILES[$name]["name"] != ""){
			$extension = CommonUtils::getExtension($_FILES[$name]["name"]);
			if (!empty($extension) && ($extension == 'flv') || ($extension == 'swf'))
			{
				// Calulate name of picture
				$video = date('Y-m') . CommonUtils::randomNumber(9) . '.' . $extension;

				// MAX 200MB
				ini_set('upload_max_filesize', '200M');

				// Copy to server
				if(!copy($_FILES[$name]["tmp_name"], UPLOADIMAGE_PATH . '/Images/' . $video)){
					$video = "";
					throw new Exception('Upload video fail', 1);
				}
			}
			else
			{
				$video = "";
				throw new Exception('Upload video fail', 2);
			}
		}
		return $video;
	}

	public static function normaliza ($string)
	{
		/*$a = 'À�?ÂÃÄÅÆÇÈÉÊËÌ�?Î�?�?ÑÒÓÔÕÖØÙÚÛÜ�?ÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûýýþÿŔŕ';
		 $b = 'aaaaaaaceeeeiiiidnoooooouuuuybsaaaaaaaceeeeiiiidnoooooouuuyybyRr';
		 $string = strtr($string, $a, $b);
		 return strtolower($string);*/
		$string = utf8_encode($string);
		$table = array(
	        'Š'=>'S', 'š'=>'s', '�?'=>'Dj', 'đ'=>'dj', 'Ž'=>'Z', 'ž'=>'z', 'Č'=>'C', '�?'=>'c', 'Ć'=>'C', 'ć'=>'c',
	        'À'=>'A', '�?'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E',
	        'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', '�?'=>'I', 'Î'=>'I', '�?'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O',
	        'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', '�?'=>'Y', 'Þ'=>'B', 'ß'=>'Ss',
	        'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e',
	        'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o',
	        'ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b',
	        'ÿ'=>'y', 'Ŕ'=>'R', 'ŕ'=>'r',
		);

		return strtr($string, $table);
	}

	public static function imageFormatSize($fileName,$maxWidth = 0, $maxHeight = 0)
	{
		if (file_exists($fileName)){
			list($w,$h,$type,$attr) = getimagesize($fileName);
			if(!isset($w) || !isset($h) || $w == 0 || $h == 0){
				$w = 0;
				$h = 0;
				return array(0,0);
			}
			if($maxWidth == 0){
				$maxWidth = $w;
			}
			if($maxHeight == 0){
				$maxHeight = $h;
			}
			if($maxWidth == 0 || $maxHeight == 0){
				return array($w,$h);
			}else{
				if($w > $maxWidth){
					$h = (int)($maxWidth * $h/$w);
					$w = $maxWidth;
				}
				if($h > $maxHeight){
					$w = (int)($maxHeight * $w/$h);
					$h = $maxHeight;
				}
				return array($w,$h);
			}
		}else{
			return array(0,0);
		}
	}

	public static function man_MIME2Ext_Image($mime)
	{
		switch($mime)
		{
			case "image/gif" :
				return "gif";
			case "image/pjpeg" :
				return "jpg";
			case "image/jpeg" :
				return "jpg";
			case "image/png" :
				return "png";
		}
		return "";
	}

	public static function man_MIME2Ext_Ico($mime)
	{
		switch($mime)
		{
			case "image/png" :
				return "png";
			case "image/x-icon" :
				return "ico";
		}
		return "";
	}

	public static function man_MIME2Ext_Zip($mime)
	{
		switch($mime)
		{
			case "application/zip" :
				return "zip";
		}
		return "";
	}

	public static function randomNumber($number)
	{
		if($number)
		{
			$total = "";
			for($i=1;$i<=$number;$i++)
			{
				$nr=rand(0,9);
				$total=$total.$nr;
			}
		}
		return $total;
	}

	/**
	 * Redirect
	 *
	 * @param string $url
	 */
	public static function redirect($url)
	{
		if(headers_sent()){
			echo "<script>document.location.href='$url';</script>";
		}else{
			header( 'HTTP/1.1 301 Moved Permanently' );
			header("Location: " . $url);
		}
	}

	/**
	 * Get IP address of the client
	 *
	 * @return string ip address of the client
	 */
	public static function getIP()
	{
		if(isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
			if (isset($_SERVER["HTTP_CLIENT_IP"])) {
				$proxy = $_SERVER["HTTP_CLIENT_IP"];
			} else {
				$proxy = $_SERVER["REMOTE_ADDR"];
			}
			$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
		}else {
			if (isset($_SERVER["HTTP_CLIENT_IP"])) {
				$ip = $_SERVER["HTTP_CLIENT_IP"];
			} else {
				$ip = $_SERVER["REMOTE_ADDR"];
			}
		}
		return $ip;
	}

	/*
	 * function: formatDate
	 * input: (date: Y-m-d , format:option)
	 * output: date: format
	 */
	public static function formatDate($date, $format)
	{
		if(!isset($date) || trim($date) == "" || substr($date, 0, 10) == "0000-00-00" || substr($date, 0, 10) == "0000/00/00"){
			return "";

		}

		$y = substr($date, 0, 4);

		$m = substr($date, 5, 2);

		$d = substr($date, 8, 2);

		$s = (int) substr($date, -2, 2);

		$i = (int) substr($date, -5, 2);

		$h = (int) substr($date, -7, 2);

		return date($format, mktime($h,$i,$s,$m,$d,$y));

	}

	/**
	 * Format $date with $format option
	 *
	 * @param $date: USA date: m-d-Y or m/d/Y
	 * @param $format
	 *
	 * @return date object
	 */
	public static function formatUSADate($date, $format)
	{
		if (!preg_match('/^(\d{1,2})[\/-](\d{1,2})[\/-](\d{4})$/', $date, $matches)) {
			return '';

		}

		return date($format, mktime(0, 0, 0, $matches[1], $matches[2], $matches[3]));

	}

	public static function compareDate($date1, $date2)
	{

		$y1 = substr($date1, 0, 4);

		$m1 = substr($date1, 5, 2);

		$d1 = substr($date1, 8, 2);

		$y2 = substr($date2, 0, 4);

		$m2 = substr($date2, 5, 2);

		$d2 = substr($date2, 8, 2);

		if ($y1 < $y2) return -1;

		else if($y1 > $y2) return 1;

		else {

			if ($m1 < $m2) return -1;

			else if ($m1 > $m2) return 1;

			else {

				if ($d1 < $d2) return -1;

				else if($d1 > $d2) return 1;

				else return 0;

			}

		}
		return 0;
	}

	public static function formatDecNumber($value,$point=0)
	{
		$res = number_format($value, $point, '.', ',');
		return $curr . $res;
	}

	public static function duration($date1, $date2, $split = "/")
	{
		list($y1, $m1, $d1) = explode($split, $date1);

		list($y2, $m2, $d2) = explode($split, $date2);

		$res =  abs((int)((mktime(0, 0, 0, $m1, $d1, $y1) - mktime(0, 0, 0, $m2, $d2, $y2)) / (24 * 3600)));

		return $res;
	}



	/**
	 * @desc Funtion addDate
	 *       $date : Y-m-d
	 */
	public static function addDate($date, $more = 0)
	{
		if ($date == ""){
			return "";
		}

		list($y, $m, $d) = explode('-', $date);

		$res = date("Y-m-d", mktime(0, 0, 0, $m, $d, $y) + $more * 3600 * 24);

		return $res;
	}

	/**
	 * @desc Funtion addDate
	 *       $date : Y-m-d
	 */
	public static function addMonth($date, $more = 0)
	{
		if ($date == ""){
			return "";
		}
		list($y, $m, $d) = explode('-', $date);

		$res = date("Y-m-d", mktime(0, 0, 0, $m, $d, $y) + $more * 3600 * 24);

		return $res;
	}


	public static function formatCurrency($value, $curr = '$')
	{
		$res = number_format($value, 2, '.', ',');
		return $curr . $res;
	}

	public static function getExtension($str)
	{
		$i = strrpos($str,".");
		if (!$i){
			return "";
		}

		$l = strlen($str) - $i;
		$ext = substr($str,$i+1,$l);

		// Return extension
		return strtolower($ext);
	}

	/**
	 * Checking whether the filetype is Image file or not
	 * @param $extension : File type
	 * @return true if filetype is image otherwise return false
	 */
	public static function isImageFile($extension)
	{
		$extension = strtolower($extension);
		if ($extension == ".jpg" || $extension == ".png" || $extension == ".gif"){
			return true;
		}
		return false;
	}

	/**
	 * Delete a file
	 * @param $filename String : name of file
	 * @param $path String: directory of file
	 * @return SUCC if filename is deleted, otherwise return ERROR
	 */
	public static function delFile($filename, $path)
	{
		$delres = @unlink($path . "/" .  $filename);
		if ($delres) {
			return SUCC;
		}
		else {
			return ERROR;
		}
	}

	/**
	 * Upload file onto Server
	 * @param $source String
	 * @param $des String
	 * @param $path String
	 * @param $width Int
	 * @param $height Int
	 * @param $max_size Int
	 * @return fileName is uploaded otherwise return ERROR
	 */
	public static function uploadFile($fileName, $path, $width, $height, $max_size)
	{
		// Check exist file
		if (!isset($_FILES) || !is_array($_FILES[$fileName]) || !$_FILES[$fileName]['name']) {
			return ERROR;
		}

		// Check file type extention
		$extention = substr($_FILES[$fileName]['name'], strrpos($_FILES[$fileName]['name'], '.'));
		if (!(CommonUtils::isImageFile($extention))){
			return ERROR;
		}

		// Validate file size
		$width = 0;
		$height = 0;
		$max_size = 0;
		// End validate file size
		$imageName = "";
		$imageName =  CommonUtils::randomNumber(8).$_FILES[$fileName]['name'];
		//die($path . "/" . $imageName);
		if(!copy($_FILES[$fileName]['tmp_name'], $path . "/" . $imageName)){
			$imageName = "";
			return ERROR;
		}
		return $imageName;
	}

	/**
	 * Check valid email
	 * @param string $email
	 * @return int $rturn
	 */
	public static function isValidEmail($email){
		return eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email);
	}


	public static function uploadTemplate($name)
	{
		$template = "";
		if(isset($_FILES[$name]["name"]) && $_FILES[$name]["name"] != ""){
			$extension = CommonUtils::getExtension($_FILES[$name]["name"]);
			if (!empty($extension) && ($extension == 'zip'))
			{

				$template = 'template' . CommonUtils::randomNumber(9) . '.' . $extension;

				// Copy to server
				if(!copy($_FILES[$name]["tmp_name"], UPLOADTEMPLATE_PATH .'/'. $template)){
					$template = "";
					throw new Exception('Upload image fail', 1);
				}
			}
			else
			{
				$template = "";
				throw new Exception('Upload ZIP file fail', 2);
			}
		}
		return $template;
	}

	public static function detect_mobile()
	{	
		$_SERVER['ALL_HTTP'] = isset($_SERVER['ALL_HTTP']) ? $_SERVER['ALL_HTTP'] : '';
		
		$mobile_browser = '0';

		if(preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|iphone|ipad|ipod|android|xoom)/i', strtolower($_SERVER['HTTP_USER_AGENT']))){
			$mobile_browser++;
		}

		if((isset($_SERVER['HTTP_ACCEPT'])) and (strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml') !== false)){
			$mobile_browser++;
		}		

		if(isset($_SERVER['HTTP_X_WAP_PROFILE'])){
			$mobile_browser++;
		}

		if(isset($_SERVER['HTTP_PROFILE'])){
			$mobile_browser++;
		}

		$mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'],0,4));
		$mobile_agents = array(
                        'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac',
                        'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno',
                        'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-',
                        'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-',
                        'newt','noki','oper','palm','pana','pant','phil','play','port','prox',
                        'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar',
                        'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-',
                        'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp',
                        'wapr','webc','winw','winw','xda','xda-'
                        );

                        if(in_array($mobile_ua, $mobile_agents)){
                        	$mobile_browser++;
                        }

                        if(strpos(strtolower($_SERVER['ALL_HTTP']), 'operamini') !== false){
                        	$mobile_browser++;
                        }

                        // Pre-final check to reset everything if the user is on Windows
                        if(strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows') !== false){
                        	$mobile_browser=0;
                        }

                        // But WP7 is also Windows, with a slightly different characteristic
                        if(strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows phone') !== false){
                        	$mobile_browser++;
                        }

                        if($mobile_browser>0){
                        	return true;
                        }
                        else{
                        	return false;
                        }
	}
}